package org.soenea.doitall.application;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.dsrg.soenea.uow.MapperFactory;
import org.dsrg.soenea.uow.UoW;
import org.soenea.doitall.application.dispatcher.Dispatcher;
import org.soenea.doitall.domain.model.group.Group;
import org.soenea.doitall.domain.model.group.mapper.GroupOutputMapper;
import org.soenea.doitall.domain.model.invite.Invite;
import org.soenea.doitall.domain.model.invite.mapper.InviteOutputMapper;
import org.soenea.doitall.domain.model.user.User;
import org.soenea.doitall.domain.model.user.mapper.UserOutputMapper;

public class FrontController extends SampleHttpServlet {
	private static final long serialVersionUID = 1L;

	@Override
	public void init() throws ServletException {
		super.init();
		
		MapperFactory fac = new MapperFactory();
		
		fac.addMapping(User.class, UserOutputMapper.class);
		fac.addMapping(Group.class, GroupOutputMapper.class);
		fac.addMapping(Invite.class, InviteOutputMapper.class);
		
		UoW.initMapperFactory(fac);
	}	
	
	protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		UoW.newCurrent(); 		
		Dispatcher fc = getFrontCommand(request);
		if (fc == null) {
			String msg = "Invalid or unspecified command";
			if (request.getAttribute("command") != null)
				msg += " (" + request.getParameter("command") + ")";
			response.sendError(HttpServletResponse.SC_NOT_FOUND, msg);
		} else {
			fc.init(request, response);
			fc.execute();
		}
	}

	private Dispatcher getFrontCommand(HttpServletRequest request) {
		try {
			String command = (String)request.getAttribute("command");
			
			if (command == null || command.isEmpty()) {
				return null;
			}
			String fqCommand = "org.soenea.doitall.application.dispatcher."
					+ command;
			return (Dispatcher) Class.forName(fqCommand).newInstance();
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
}
